package com.msc.util;

import io.netty.util.internal.StringUtil;
import org.apache.commons.lang3.StringUtils;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.regex.Pattern;

/**
 * @author masc
 * @date 2022-07-18 17:42
 * <p></p>
 */
public class DateUtil {
    /**
     * 系统默认的格式化字符串
     */
    public static final String defaultDateFormatStr = "yyyy-MM-dd";
    public static final String DATE_FORMAT_DATE1 = "yyyyMMdd";
    /**
     * 系统默认的格式化字符串
     */
    private static final String defaultTimeFormatStr = "yyyy-MM-dd HH:mm:ss";
    public static final String DATE_FORMAT_DATETIME1 = "yyyyMMddHHmmss";
    public static final String DATE_FORMAT_DATETIME2 = "yyyy-MM-dd HH:mm:ss";
    public static final String DATE_FORMAT_DATETIME3 = "yyyy-MM-dd HH:mm";
    public static final String DATE_FORMAT_DATETIME5 = "HH:mm";
    public static final String DATE_FORMAT_DATETIME6 = "MM-dd HH:mm";
    //日期校验 格式yyyy-mm-dd
    public static final String DATE_FORMAT_DATETIME4 = "yyyy/MM/dd HH:mm";
    public static final String regex = "((19|20)[0-9]{2})-(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01])";
    //日期校验 允许/ - . 分割符
    public static final String dateReg = "^(?:(?!0000)[0-9]{4}([-/.]?)(?:(?:0?[1-9]|1[0-2])\\1(?:0?[1-9]|1[0-9]|2[0-8])|(?:0?[13-9]|1[0-2])\\1(?:29|30)|(?:0?[13578]|1[02])\\1(?:31))|(?:[0-9]{2}(?:0[48]|[2468][048]|[13579][26])|(?:0[48]|[2468][048]|[13579][26])00)([-/.]?)0?2\\2(?:29))$";

    public static final String[] weekDays_1 = {"星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"};
    public static final String[] weekDays_2 = {"周日", "周一", "周二", "周三", "周四", "周五", "周六"};


    //校验年份不可大于9999
    public static boolean isValidDate(String dateStr) {
        return dateStr.matches(dateReg);
    }

    /**
     * 日期转字符串
     *
     * @param date      日期
     * @param formatStr 格式化字符串
     * @return 字符换
     */
    public static String dateToString(Date date, String formatStr) {
        DateFormat df = new SimpleDateFormat(formatStr);
        return df.format(date);
    }

    /**
     * 日期转字符串
     *
     * @param localDateTime 日期
     * @param formatStr     格式化字符串
     * @return 字符换
     */
    public static String dateToString(LocalDateTime localDateTime, String formatStr) {
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(formatStr);
        return dateTimeFormatter.format(localDateTime);
    }

    /**
     * 字符串转日期
     *
     * @param dateTimeStr
     * @param formatStr
     * @return
     */
    public static LocalDateTime parseDateTimeStr(String dateTimeStr, String formatStr) {
        return LocalDateTime.parse(dateTimeStr, DateTimeFormatter.ofPattern(formatStr));
    }

    /**
     * 字符串转换到时间格式
     *
     * @param dateStr   需要转换的字符串
     * @param formatStr 需要格式的目标字符串 比如 yyyy-MM-dd
     * @return Date 返回转换后的时间
     */
    public static Date stringToDate(String dateStr, String formatStr) {
        DateFormat sdf = new SimpleDateFormat(formatStr);
        Date date = null;
        try {
            date = sdf.parse(dateStr);
        } catch (ParseException e) {
        }
        return date;
    }

    /**
     * 判断时间是否在[startTime, endTime]区间，注意时间格式要一致
     *
     * @param time      时间
     * @param startTime 开始时间
     * @param endTime   结束时间
     * @return
     * @author jqlin
     */
    public static boolean isEffectiveDate(Date time, String startTime, String endTime, String formatStr) {
        if (time.getTime() == stringToDate(startTime, formatStr).getTime()
                || time.getTime() == stringToDate(endTime, formatStr).getTime()) {
            return true;
        }
        Calendar date = Calendar.getInstance();
        date.setTime(time);

        Calendar begin = Calendar.getInstance();
        begin.setTime(stringToDate(startTime, formatStr));

        Calendar end = Calendar.getInstance();
        end.setTime(stringToDate(endTime, formatStr));

        if (date.after(begin) && date.before(end)) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 取得系统时间，格式为yyyy-MM-dd HH:mm:ss
     *
     * @return 系统时间
     */
    public static String getSystemTime() {
        String strTime = "";
        DateFormat df = new SimpleDateFormat(defaultTimeFormatStr);
        strTime = df.format(new Date());
        return strTime;
    }

    /**
     * 取得系统日期，格式为yyyy-MM-dd
     *
     * @return 系统日期
     */
    public static String getSystemDate() {
        String strDate = "";
        SimpleDateFormat df = new SimpleDateFormat(defaultDateFormatStr);
        strDate = df.format(new Date());
        return strDate;
    }


    /**
     * 取得系统时间
     *
     * @return 系统时间
     */
    public static String getShortSystemTime() {
        String strTime = "";
        DateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
        strTime = df.format(new Date());
        return strTime;
    }


    /**
     * 取得系统短日期，yyyyMMdd
     *
     * @return 系统短日期
     */
    public static String getShortSystemDate() {
        String strTime = "";
        DateFormat df = new SimpleDateFormat("yyyyMMdd");
        strTime = df.format(new Date());
        return strTime;
    }

    /**
     * 系统时间加减
     *
     * @param date      当前日期
     * @param dayNum    加减的日期数
     * @param formatStr 格式化字符串
     * @return 时间加减
     */
    public static String getOperaDate(String date, int dayNum, String formatStr) {
        Date dt = null;
        SimpleDateFormat df = new SimpleDateFormat(formatStr);
        try {
            dt = df.parse(date);
        } catch (ParseException e) {

         }
        GregorianCalendar gc = new GregorianCalendar();
        gc.setTime(dt);
        gc.add(5, dayNum);
        return df.format(gc.getTime());
    }

    /**
     * 系统时间加减，默认日期格式
     *
     * @param date   当前日期
     * @param dayNum 加减的日期数
     * @return 系统时间加减
     */
    public static String getOperaDate(String date, int dayNum) {
        return getOperaDate(date, dayNum, defaultDateFormatStr);
    }

    public static Date getOperaDate(Date date, int dayNum) {
        Calendar instance = Calendar.getInstance();
        instance.setTime(date);
        instance.add(Calendar.DAY_OF_MONTH, dayNum);
        return instance.getTime();
    }

    /**
     * 系统月份加减
     *
     * @param date      日期字符串
     * @param monthNum  月份数
     * @param formatStr 格式化字符串
     * @return 系统月份加减
     */
    public static String getOperaMonth(String date, int monthNum, String formatStr) {
        Date dt = null;
        SimpleDateFormat df = new SimpleDateFormat(formatStr);
        try {
            dt = df.parse(date);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        GregorianCalendar gc = new GregorianCalendar();
        gc.setTime(dt);
        gc.add(2, monthNum);
        return df.format(gc.getTime());
    }

    /**
     * 系统月份加减
     *
     * @param date     日期
     * @param monthNum 月份数
     * @return 系统月份加减
     */
    public static String getOperaMonth(String date, int monthNum) {
        return getOperaMonth(date, monthNum, defaultDateFormatStr);
    }

    public static Date getOpetaMinute(String date, int minuteNum, String formatStr) {
        Date dt = null;
        SimpleDateFormat df = new SimpleDateFormat(formatStr);
        try {
            dt = df.parse(date);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        GregorianCalendar gc = new GregorianCalendar();
        gc.setTime(dt);
        gc.add(Calendar.MINUTE, minuteNum);
        return gc.getTime();
    }

    /**
     * 取得两个日期的时间差
     *
     * @param date1     日期1
     * @param date2     日期2
     * @param formatStr 格式化字符串
     * @return 取得两个日期的时间差
     */
    public static int getDateDifference(String date1, String date2, String formatStr) {
        SimpleDateFormat formatter = new SimpleDateFormat(formatStr);
        ParsePosition pos = new ParsePosition(0);
        ParsePosition pos1 = new ParsePosition(0);
        Date dt1 = formatter.parse(date1, pos);
        Date dt2 = formatter.parse(date2, pos1);
        int l = (int) ((dt2.getTime() - dt1.getTime()) / (3600 * 24 * 1000));
        return l;
    }

    /**
     * 取得两个日期的时间差，两个都是字符串
     *
     * @param date1 日期1
     * @param date2 日期2
     * @return 取得两个日期的时间差
     */
    public static int getDateDifference(String date1, String date2) {
        return getDateDifference(date1, date2, defaultDateFormatStr);
    }


    /**
     * 取得两个日期的时间差,两个都是日期型
     *
     * @param date1 日期1
     * @param date2 日期2
     * @return 取得两个日期的时间差
     */
    public static int getHourDifference(Date date1, Date date2) {
        int l = (int) (date1.getTime() - date2.getTime()) / (3600 * 1000);
        return l;
    }

    /**
     * 取得两个日期的秒数差,两个都是日期型
     *
     * @param date1 日期1
     * @param date2 日期2
     * @return 取得两个日期的秒数差
     */
    public static int getSecondDifference(Date date1, Date date2) {
        int l = (int) (date1.getTime() - date2.getTime()) / 1000;
        return l;
    }

    /**
     * 取得两个日期的月份差
     *
     * @param date1     日期1
     * @param date2     日期2
     * @param formatStr 格式化字符换
     * @return 取得两个日期的月份差
     */
    public static int getMonthDifference(String date1, String date2, String formatStr) {
        int result = 0;
        SimpleDateFormat sdf = new SimpleDateFormat(formatStr);
        Calendar c1 = Calendar.getInstance();
        Calendar c2 = Calendar.getInstance();
        try {
            c1.setTime(sdf.parse(date1));
            c2.setTime(sdf.parse(date2));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        result = c2.get(Calendar.MONTH) - c1.get(Calendar.MONTH);
        return result == 0 ? 1 : Math.abs(result);
    }

    /**
     * 取得两个日期的月份差
     *
     * @param date1 日期1
     * @param date2 日期2
     * @return 取得两个日期的月份差
     */
    public static int getMonthDifference(String date1, String date2) {
        int result = 0;
        SimpleDateFormat sdf = new SimpleDateFormat(defaultDateFormatStr);
        Calendar c1 = Calendar.getInstance();
        Calendar c2 = Calendar.getInstance();
        try {
            c1.setTime(sdf.parse(date1));
            c2.setTime(sdf.parse(date2));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        result = c2.get(Calendar.MONTH) - c1.get(Calendar.MONTH);
        return result;
    }

    /**
     * 取得当月最后一天
     *
     * @return 取得当月最后一天
     */
    public static String getLastDayOfMonth() {
        Calendar cal = Calendar.getInstance();
        // 年
        cal.set(Calendar.YEAR, cal.get(Calendar.YEAR));
        // 月，因为Calendar里的月是从0开始，所以要减1
        cal.set(Calendar.MONTH, cal.get(Calendar.MONTH));
        // 日，设为一号
        cal.set(Calendar.DATE, 1);
        // 月份加一，得到下个月的一号
        cal.add(Calendar.MONTH, 1);
        // 下一个月减一为本月最后一天
        cal.add(Calendar.DATE, -1);
        return new SimpleDateFormat(defaultDateFormatStr).format(cal.getTime());
    }

    /**
     * 取得当月第一天
     *
     * @return 取得当月第一天
     */
    public static String getFirstDayOfMonth() {
        Calendar cal = Calendar.getInstance();
        // 年
        cal.set(Calendar.YEAR, cal.get(Calendar.YEAR));
        // 月，因为Calendar里的月是从0开始，所以要减1
        cal.set(Calendar.MONTH, cal.get(Calendar.MONTH));
        // 日，设为一号
        cal.set(Calendar.DATE, 1);
        String df = new SimpleDateFormat(defaultDateFormatStr).format(cal.getTime());
        // 获得月初是几号
        return df;
    }

    /**
     * 取得上个月的第一天
     *
     * @return 取得上个月的第一天
     */
    public static String getFirstDayOfLastMonth() {
        Calendar cal = Calendar.getInstance();
        // 年
        cal.set(Calendar.YEAR, cal.get(Calendar.YEAR));
        // 月，因为Calendar里的月是从0开始，所以要减1
        cal.set(Calendar.MONTH, cal.get(Calendar.MONTH));
        // 日，设为一号
        cal.set(Calendar.DATE, 1);
        // 月份减一，得到上个月的一号
        cal.add(Calendar.MONTH, -1);
        String df = new SimpleDateFormat(defaultDateFormatStr).format(cal.getTime());
        // 获得月初是几号
        return df;
    }

    /**
     * 取得下个月的最后一天
     *
     * @return 取得下个月的最后一天
     */
    public static String getLastDayOfNextMonth() {
        Calendar cal = Calendar.getInstance();
        // 年
        cal.set(Calendar.YEAR, cal.get(Calendar.YEAR));
        // 月，因为Calendar里的月是从0开始，所以要减1
        cal.set(Calendar.MONTH, cal.get(Calendar.MONTH));
        // 日，设为一号
        cal.set(Calendar.DATE, 1);
        // 月份加一，得到下下个月的一号
        cal.add(Calendar.MONTH, 2);
        // 下下一个月减一为下个月最后一天
        cal.add(Calendar.DATE, -1);
        String df = new SimpleDateFormat(defaultDateFormatStr).format(cal.getTime());
        // 获得月末是几号
        return df;
    }


    /**
     * 取得当月最后一天
     *
     * @param date 当前日期
     * @return 取得当月最后一天
     */
    public static String getLastDayOfMonth(String date) {
        Date dt = null;
        SimpleDateFormat df = new SimpleDateFormat(defaultDateFormatStr);
        try {
            dt = df.parse(date);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        Calendar cal = Calendar.getInstance();
        cal.setTime(dt);
        // 年
        cal.set(Calendar.YEAR, cal.get(Calendar.YEAR));
        // 月，因为Calendar里的月是从0开始，所以要减1
        cal.set(Calendar.MONTH, cal.get(Calendar.MONTH));
        // 日，设为一号
        cal.set(Calendar.DATE, 1);
        // 月份加一，得到下个月的一号
        cal.add(Calendar.MONTH, 1);
        // 下一个月减一为本月最后一天
        cal.add(Calendar.DATE, -1);
        // 获得月末是几号
        return df.format(cal.getTime());
    }

    /**
     * 获取某个时间段的所有天数集合(包含起始日期与终止日期)
     *
     * @param starDate 起始日期
     * @param endDate  终止日期
     * @return 列表
     */
    public static List<String> getDayList(String starDate, String endDate) {
        SimpleDateFormat format = new SimpleDateFormat(defaultDateFormatStr);
        List<String> dayList = new ArrayList<String>();
        if (starDate.equals(endDate)) {
            dayList.add(starDate);
        } else if (starDate.compareTo(endDate) < 0) {
            while (starDate.compareTo(endDate) <= 0) {
                dayList.add(starDate);
                long l = stringToDate(starDate, "yyyy-MM-dd").getTime();
                starDate = format.format(l + 3600 * 24 * 1000);
            }
        } else {
            dayList.add(endDate);
        }
        return dayList;
    }

    public static Date removeHhMmSs(Date date) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date date01 = null;
        try {
            String s = sdf.format(date);
            date01 = sdf.parse(s);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return date01;
    }

    /**
     * 去除时间秒
     *
     * @param date
     * @return
     */
    public static Date removeSs(Date date) {
        SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT_DATETIME3);
        Date date01 = null;
        try {
            String s = sdf.format(date);
            date01 = sdf.parse(s);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return date01;
    }

    /**
     * 获取当前系统时间并格式化
     *
     * @param format 格式化规则
     * @return
     */
    public static String getCurrentTime(String format) {
        SimpleDateFormat df = new SimpleDateFormat(format);
        return df.format(new Date());
    }

    /**
     * 获取日期是周几
     *
     * @param datetime
     * @return
     */
    public static String dateToWeek(String datetime, String[] weekDays) {
        SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd");
        Calendar cal = Calendar.getInstance(); // 获得一个日历
        Date datet = null;
        try {
            datet = f.parse(datetime);
            cal.setTime(datet);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        int w = cal.get(Calendar.DAY_OF_WEEK) - 1; // 指示一个星期中的某天。
        if (w < 0) {
            w = 0;
        }
        return weekDays[w];
    }

    /**
     * 获取下一个周几的日期
     *
     * @param count
     * @return
     */
    public static String getNextWeekDay(int count) {
        //获取当前时间是周几
        int week = Integer.valueOf(String.valueOf(DateUtil.dateToIntWeek(DateUtil.getSystemTime())));
        Calendar strDate = Calendar.getInstance();
        strDate.add(strDate.DATE, 7 + count - week);

        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        String preMonday = df.format(strDate.getTime());
        return preMonday;
    }

    public static String dateToWeek(String datetime) {
        return dateToWeek(datetime, weekDays_1);
    }

    public static String dateToWeek2(String datetime) {
        return dateToWeek(datetime, weekDays_2);
    }


    /**
     * 获取一个时间范围的每一天返回LIST
     *
     * @param beginTime
     * @param endTime
     * @return
     * @throws ParseException
     */
    public static List<String> getDateRegionList(String beginTime, String endTime) {
        List<String> list = new ArrayList<>();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date dateOne = null;
        Date dateTwo = null;
        try {
            dateOne = dateFormat.parse(beginTime);
            dateTwo = dateFormat.parse(endTime);
        } catch (ParseException e) {
            e.printStackTrace();
            return null;
        }
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(dateOne);
        while (!calendar.getTime().after(dateTwo)) {
            String format = dateFormat.format(calendar.getTime());
            list.add(format + DateUtil.dateToWeek(format));
            calendar.add(Calendar.DAY_OF_MONTH, 1);
        }
        return list;
    }


    /**
     * 获取本周，上周，下周的第一天或最后一天
     *
     * @param weekNo L(上一周) N(下一周) C(本周)
     * @param dayNo  F(第一天) L(最后一天)
     * @return
     */
    public static String getDayWeek(String weekNo, String dayNo) {

        SimpleDateFormat df = new SimpleDateFormat(defaultDateFormatStr);
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.YEAR, cal.get(Calendar.YEAR));
        cal.set(Calendar.MONTH, cal.get(Calendar.MONTH));
        cal.set(Calendar.WEEK_OF_MONTH, cal.get(Calendar.WEEK_OF_MONTH));
        //从周一开始，所以加2（默认周日开始）
        cal.set(Calendar.DAY_OF_WEEK, 2);

        switch (weekNo) {
            case "C":
                break;
            case "L":
                cal.add(Calendar.WEEK_OF_MONTH, -1);
                break;
            case "N":
                cal.add(Calendar.WEEK_OF_MONTH, 1);
                break;
            default:
                throw new IllegalArgumentException("weekNo param error!");

        }
        switch (dayNo) {
            case "F":
                return df.format(cal.getTime());
            case "L":
                cal.add(Calendar.DAY_OF_WEEK, 6);
                return df.format(cal.getTime());
            default:
                throw new IllegalArgumentException("dayNo param error!");
        }

    }

    /**
     * 从date 或 String (yyyy-MM-dd HH:mm:ss)类型的日期中获取年、月、日、小时和分钟
     * 例如：从2018-09-21 08:00:00中获取2018-09-21 08:00
     *
     * @return
     */
    public static String getHourAndMinutes(Date date, String dateStr) {
        String ymdhm = "";
        if (date != null && StringUtil.isNullOrEmpty(dateStr)) {
            Calendar c = Calendar.getInstance();
            //获取年月日
            String ymd = DateUtil.dateToString(date, DateUtil.defaultDateFormatStr);
            c.setTime(date);
            Integer h = c.get(Calendar.HOUR_OF_DAY);
            Integer m = c.get(Calendar.MINUTE);
            String hour = null;
            String minute = null;
            if (h.toString().length() == 1) {
                hour = "0" + h;
            } else {
                hour = h + "";
            }
            if (m.toString().length() == 1) {
                minute = "0" + m;
            } else {
                minute = m + "";
            }
            ymdhm = ymd + " " + hour + ":" + minute;
        } else if (StringUtils.isNotEmpty(dateStr)) {
            ymdhm = dateStr.substring(0, 16);
        }
        return ymdhm;
    }

    /**
     * 从date类型的日期中获取小时和分钟
     * 例如：从2018-09-21 08:00:00中获取小时分钟08:00
     *
     * @return
     */
    public static String getHourAndMinutesFromDate(Date date) {

        Calendar c = Calendar.getInstance();
        c.setTime(date);
        Integer h = c.get(Calendar.HOUR_OF_DAY);
        Integer m = c.get(Calendar.MINUTE);
        String hour = null;
        String minute = null;
        if (h.toString().length() == 1) {
            hour = "0" + h;
        } else {
            hour = h + "";
        }
        if (m.toString().length() == 1) {
            minute = "0" + m;
        } else {
            minute = m + "";
        }
        return hour + ":" + minute;
    }

    /**
     * 从date类型的日期中获取小时、分钟和秒
     * 例如：从2018-09-21 08:00:00中获取小时分钟08:00:00
     *
     * @return
     */
    public static String getHourAndMinAndSec(Date date) {

        Calendar c = Calendar.getInstance();
        c.setTime(date);
        Integer h = c.get(Calendar.HOUR_OF_DAY);
        Integer m = c.get(Calendar.MINUTE);
        Integer s = c.get(Calendar.SECOND);
        String hour = null;
        String minute = null;
        String second = null;
        if (h.toString().length() == 1) {
            hour = "0" + h;
        } else {
            hour = h + "";
        }
        if (m.toString().length() == 1) {
            minute = "0" + m;
        } else {
            minute = m + "";
        }
        if (s.toString().length() == 1) {
            second = "0" + s;
        } else {
            second = s + "";
        }
        return hour + ":" + minute + ":" + second;
    }

    /**
     * 比较时间大小
     *
     * @param hm1
     * @param hm2
     * @return
     */
    public static boolean compareDate(String hm1, String hm2, String format) {
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        Date time01 = null;
        Date time02 = null;
        try {
            time01 = sdf.parse(hm1);
            time02 = sdf.parse(hm2);
            //Date类的一个方法，如果time01早于time02返回true，否则返回false
            if (time01.before(time02)) {
                return true;
            }
            if (time01.equals(time02)) {
                return true;
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 比较时间大小
     *
     * @param time01
     * @param time02
     * @return
     */
    public static boolean compareDate(Date time01, Date time02) {
        try {
            //Date类的一个方法，如果time01早于time02返回true，否则返回false
            if (time01.before(time02)) {
                return true;
            }
            if (time01.equals(time02)) {
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 比较时间和分钟
     *
     * @param hm1 格式 0800
     * @param hm2
     * @return
     */
    public static int compareHourAndMin(String hm1, String hm2) {
        String h1 = hm1.substring(0, 2);
        String h2 = hm2.substring(0, 2);
        String m1 = hm1.substring(2);
        String m2 = hm2.substring(2);

        if (Integer.valueOf(h1) > Integer.valueOf(h2)) {
            return 1;
        } else if (Integer.valueOf(h1) < Integer.valueOf(h2)) {
            return -1;
        } else {
            if (Integer.valueOf(m1) > Integer.valueOf(m2)) {
                return 1;
            } else if (Integer.valueOf(m1) < Integer.valueOf(m2)) {
                return -1;
            } else {
                return 0;
            }
        }
    }

    /**
     * 从date类型的日期中获取小时
     * 例如：从2018-09-21 08:00:00中获取小时08
     *
     * @return
     */
    public static String getHour(Date date) {
        Calendar c = Calendar.getInstance();
        c.setTime(date);
        Integer h = c.get(Calendar.HOUR_OF_DAY);
        String hour = null;
        if (h.toString().length() == 1) {
            hour = "0" + h;
        } else {
            hour = h + "";
        }
        return hour;
    }

    /**
     * 从date类型的日期中获取小时
     * 例如：从2018-09-21 08:00:00中获取小时8
     *
     * @return
     */
    public static String getPreHour(Date date) {
        Calendar c = Calendar.getInstance();
        c.setTime(date);
        Integer h = c.get(Calendar.HOUR_OF_DAY);
        return h + "";
    }


    /**
     * 从date类型的日期中获取分钟
     * 例如：从2018-09-21 08:00:00中获取分钟00
     *
     * @param date
     * @return
     */
    public static String getMin(Date date) {
        Calendar c = Calendar.getInstance();
        c.setTime(date);
        Integer m = c.get(Calendar.MINUTE);
        String minute = null;
        if (m.toString().length() == 1) {
            minute = "0" + m;
        } else {
            minute = m + "";
        }
        return minute;
    }

    /**
     * 根据小时和分钟设置date
     * 例如：小时分钟08:00 转化成日期2018-09-21 08:00:00
     *
     * @param hm
     * @return
     */
    public static Date setDateFromHourAndMinutes(String hm) {
        Date date = DateUtil.stringToDate(DateUtil.getCurrentTime(DateUtil.defaultDateFormatStr) + " " + hm + ":00", DateUtil.DATE_FORMAT_DATETIME2);
        return date;
    }

    /**
     * 根据小时和分钟设置date
     * 例如：小时分钟0800 转化成日期2018-09-21 08:00:00
     *
     * @param hm
     * @return
     */
    public static Date setDateHourAndMinutes(String hm) {
        Date date = null;
        if (!StringUtil.isNullOrEmpty(hm)) {
            String hour = hm.substring(0, 2);
            String minute = hm.substring(2);
            date = DateUtil.stringToDate(DateUtil.getCurrentTime(DateUtil.defaultDateFormatStr) + " " + hour + ":" + minute + ":00", DateUtil.DATE_FORMAT_DATETIME2);
        }
        return date;
    }

    /**
     * 根据时分秒设置date
     * 例如：时分秒08:00:00 转化成日期2018-09-21 08:00:00
     *
     * @param hm
     * @return
     */
    public static Date setDateByHMS(String hm) {
        Date date = DateUtil.stringToDate(DateUtil.getCurrentTime(DateUtil.defaultDateFormatStr) + " " + hm, DateUtil.DATE_FORMAT_DATETIME2);
        return date;
    }

    public static int compTime(Date d1, Date d2) {
        Calendar instance1 = Calendar.getInstance();
        instance1.setTime(d1);

        Calendar instance2 = Calendar.getInstance();
        instance2.setTime(d2);

        int num1 = instance1.get(Calendar.HOUR_OF_DAY) * 3600 + instance1.get(Calendar.MINUTE) * 60 + instance1.get(Calendar.SECOND);

        int num2 = instance2.get(Calendar.HOUR_OF_DAY) * 3600 + instance2.get(Calendar.MINUTE) * 60 + instance2.get(Calendar.SECOND);

        return num1 - num2;

    }

    /**
     * 给定年龄、月数、天数，推算出生日期
     *
     * @param ageYear
     * @param ageMonth
     * @param ageDay
     * @return
     */
    public static String getBirthday(int ageYear, int ageMonth, int ageDay) {
        Calendar c = Calendar.getInstance();
        c.add(Calendar.YEAR, -ageYear);
        c.add(Calendar.MONTH, -ageMonth);
        c.add(Calendar.DAY_OF_MONTH, -ageDay);
        return String.format("%tF", c.getTime());
    }

    /**
     * 给定月数、天数，推算出生日期
     *
     * @param ageMonth
     * @param ageDay
     * @return
     */
    public static String getBirthday(int ageMonth, int ageDay) {
        return getBirthday(0, ageMonth, ageDay);
    }

    /**
     * 给定出生天数，推算出生日期
     *
     * @param ageDay
     * @return
     */
    public static String getBirthday(int ageDay) {
        return getBirthday(0, 0, ageDay);
    }


    /**
     * date2比date1多的天数（不判断时分秒）
     *
     * @param date1
     * @param date2
     * @return
     */
    public static int differentDays(Date date1, Date date2) {
        Calendar cal1 = Calendar.getInstance();
        cal1.setTime(date1);

        Calendar cal2 = Calendar.getInstance();
        cal2.setTime(date2);
        int day1 = cal1.get(Calendar.DAY_OF_YEAR);
        int day2 = cal2.get(Calendar.DAY_OF_YEAR);

        int year1 = cal1.get(Calendar.YEAR);
        int year2 = cal2.get(Calendar.YEAR);
        if (year1 != year2) {
            int timeDistance = 0;
            for (int i = year1; i < year2; i++) {
                if (i % 4 == 0 && i % 100 != 0 || i % 400 == 0) {
                    timeDistance += 366;
                } else {
                    timeDistance += 365;
                }
            }

            return timeDistance + (day2 - day1);
        } else {
            //System.out.println("判断day2 - day1 : " + (day2 - day1));
            return day2 - day1;
        }
    }

    /**
     * 计算 date2 - date1 自然天差，支持date2小于date1
     * 医保计算使用
     *
     * @param date1
     * @param date2
     * @return
     */
    public static int differentDaysForMi(Date date1, Date date2) {
        Calendar cal1 = Calendar.getInstance();
        cal1.setTime(date1);
        Calendar cal2 = Calendar.getInstance();
        cal2.setTime(date2);
        int day1 = cal1.get(6);
        int day2 = cal2.get(6);
        int year1 = cal1.get(1);
        int year2 = cal2.get(1);
        if (year1 == year2) {
            return day2 - day1;
        } else {
            int diffYear = year2 - year1;
            int timeDistance = 0;
            int symbol = 1;
            int minYear = year1;
            if (diffYear < 0) {
                symbol = -1;
                minYear = year2;
            }
            for (int i = 0; i < Math.abs(diffYear); i++) {
                int year = minYear + i;
                if ((year % 4 != 0 || year % 100 == 0) && year % 400 != 0) {
                    timeDistance += 365 * symbol;
                } else {
                    timeDistance += 366 * symbol;
                }
            }
            return timeDistance + (day2 - day1);
        }
    }

    /**
     * 获取日期是周几,数字类型
     *
     * @param datetime
     * @return
     */
    public static Integer dateToIntWeek(String datetime) {
        SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd");
        Integer[] weekDays = {7, 1, 2, 3, 4, 5, 6};
        Calendar cal = Calendar.getInstance(); // 获得一个日历
        Date datet = null;
        try {
            datet = f.parse(datetime);
            cal.setTime(datet);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        int w = cal.get(Calendar.DAY_OF_WEEK) - 1; // 指示一个星期中的某天。
        if (w < 0) {
            w = 0;
        }

        return weekDays[w];
    }

    /**
     * 时间比较
     *
     * @param DATE1
     * @param DATE2
     * @return
     */
    public static int compareDate(String DATE1, String DATE2) {
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            Date dt1 = df.parse(DATE1);
            Date dt2 = df.parse(DATE2);
            if (dt1.getTime() > dt2.getTime()) {
                return 1;
            } else if (dt1.getTime() < dt2.getTime()) {
                return -1;
            } else {
                return 0;
            }
        } catch (Exception e) {
         }
        return 0;
    }


    /**
     * 给定生日计算  year + "岁" + month + "个月" + day + "天"
     *
     * @param date
     * @return
     */
    public static String getAge(Date date) {
        if (date == null) return "";
        StringBuilder age = new StringBuilder();
        Map<String, Integer> integerMap = dayCompare(date, new Date());
        if (integerMap.get("year") > 0) {
            age.append(integerMap.get("year")).append("岁");
        } else {
            if (integerMap.get("month") > 0) {
                age.append(integerMap.get("month")).append("个月");
                age.append(integerMap.get("day")).append("天");
            }
        }
        return age.toString();
    }

    /**
     * 给定生日计算年龄，不足一岁用0
     *
     * @param date
     * @return
     * @author zhaoyh 2020.4.5
     */
    public static Integer getAgeForInt(Date date) {
        if (date == null) {
            throw new IllegalArgumentException("非法的参数，日期不能为空");
        }
        Map<String, Integer> integerMap = dayCompare(date, new Date());
        if (integerMap.get("year") > 0) {
            return integerMap.get("year");
        } else {
            return 0;
        }
    }

    /**
     * 计算2个日期之间相差的  以年、月、日为单位
     *
     * @param fromDate
     * @param toDate
     * @return
     */
    public static Map<String, Integer> dayCompare(Date fromDate, Date toDate) {

        Map<String, Integer> map = new HashMap<>();
        Calendar birthday = Calendar.getInstance();
        birthday.setTime(fromDate);
        Calendar now = Calendar.getInstance();
        now.setTime(toDate);
        int day = now.get(Calendar.DAY_OF_MONTH) - birthday.get(Calendar.DAY_OF_MONTH);

        int month = now.get(Calendar.MONTH) - birthday.get(Calendar.MONTH);
        int year = now.get(Calendar.YEAR) - birthday.get(Calendar.YEAR);
        //按照减法原理，先day相减，不够向month借；然后month相减，不够向year借；最后year相减。
        if (day < 0) {
            month -= 1;
            now.add(Calendar.MONTH, -1);//得到上一个月，用来得到上个月的天数。
            day = day + now.getActualMaximum(Calendar.DAY_OF_MONTH);
        }
        if (month < 0) {
            month = (month + 12) % 12;
            year--;
        }
        StringBuffer tag = new StringBuffer();
        map.put("year", year);

        map.put("month", month);
        map.put("day", day);
        if (year == 0 && month == 0 && day == 0) {
            map.put("day", 1);
        }
        return map;
    }

    /**
     * 构造date日期
     *
     * @param yyyy
     * @param mm
     * @param dd
     * @param hh
     * @param min
     * @param s
     * @return
     */
    public static Date buildDate(int yyyy, int mm, int dd, int hh, int min, int s) {

        Calendar c = Calendar.getInstance();
        c.set(Calendar.YEAR, yyyy);
        c.set(Calendar.MONTH, mm);
        c.set(Calendar.DAY_OF_MONTH, dd);
        c.set(Calendar.HOUR_OF_DAY, hh);
        c.set(Calendar.MINUTE, min);
        c.set(Calendar.SECOND, s);
        return c.getTime();
    }

    /**
     * 获取日期的某一项
     *
     * @param date
     * @param item :Calendar.MINUTE
     * @return
     */
    public static int getDateItem(Date date, int item) {
        Calendar c = Calendar.getInstance();
        c.setTime(date);
        return c.get(item);
    }

    /**
     * 获取当日凌晨字符串（yyyy-MM-dd 00:00:00）
     *
     * @return
     */
    public static String buildDateZero() {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        Date zero = calendar.getTime();
        return dateToString(calendar.getTime(), defaultTimeFormatStr);
    }
    /**
     * 获取当前凌晨字符串（yyyy-MM-dd 00:00:00）
     *
     * @return
     */
    public static Date buildDateZero(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        return calendar.getTime();

    }
    /**
     * 获取时间年月日(2019年01月01日)
     *
     * @param date
     * @return
     */
    public static String getDateString(Date date) {
        Calendar now = Calendar.getInstance();
        now.setTime(date);
        return now.get(Calendar.YEAR) + "年" + (now.get(Calendar.MONTH) + 1) + "月" + now.get(Calendar.DAY_OF_MONTH) + "日";
    }

    /**
     * 正则表达式的匹配
     *
     * @param text 待匹配文本    @param regex 正则表达式
     */

    public static boolean match(String text, String regex) {
        if (StringUtils.isBlank(text) || StringUtils.isBlank(regex)) {
            return false;
        }
        return Pattern.compile(regex).matcher(text).matches();
    }

    /**
     * 时间增加小时
     *
     * @param day
     * @param hour
     * @return
     */
    public static String addDateHour(String day, int hour, String format) {
        SimpleDateFormat format1 = new SimpleDateFormat(format);
        Date date = null;
        try {
            date = format1.parse(day);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        if (date == null) {
            return "";
        }
        System.out.println("front:" + format1.format(date)); //显示输入的日期
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.add(Calendar.HOUR, hour);// 24小时制
        date = cal.getTime();
        System.out.println("after:" + format1.format(date));  //显示更新后的日期
        cal = null;
        return format1.format(date);

    }

    /**
     * 时间增加分钟
     *
     * @param dateStr
     * @param num     分钟数
     * @return
     */
    public static String addDateMin(String dateStr, int num) {
        Date date1 = new Date(DateUtil.stringToDate(dateStr, DateUtil.DATE_FORMAT_DATETIME3).getTime() + num * 10 * 1000 * 6);
        return DateUtil.dateToString(date1, DateUtil.DATE_FORMAT_DATETIME3);
    }

    /**
     * 时间增加秒
     *
     * @param dateStr
     * @param num
     * @return
     */
    public static String addDateSecond(String dateStr, int num) {
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date dt = sdf.parse(dateStr);

            Calendar newTime = Calendar.getInstance();
            newTime.setTime(dt);
            newTime.add(Calendar.SECOND, num);

            Date newDate = newTime.getTime();
            return sdf.format(newDate);
        } catch (Exception ex) {
            ex.printStackTrace();
            return null;
        }
    }

    /**
     * 判断当前日期是周几
     *
     * @return
     */
    public static String getWeek(Date today) {
        String week = "";
        Calendar c = Calendar.getInstance();
        c.setTime(today);
        int weekday = c.get(Calendar.DAY_OF_WEEK);
        if (weekday == 1) {
            week = "7";
        } else if (weekday == 2) {
            week = "1";
        } else if (weekday == 3) {
            week = "2";
        } else if (weekday == 4) {
            week = "3";
        } else if (weekday == 5) {
            week = "4";
        } else if (weekday == 6) {
            week = "5";
        } else if (weekday == 7) {
            week = "6";
        }
        return week;
    }

    /**
     * 获取当前时间
     *
     * @return
     */
    public static Date getCurrent() {
        LocalDateTime now = LocalDateTime.now();
        Date date = Date.from(now.atZone(ZoneId.systemDefault()).toInstant());
        return date;
    }

    /**
     * 获取昨天时间
     *
     * @return
     */
    public static String getYesterday() {
        // 获取当前日期
        LocalDate today = LocalDate.now();
        // 获取当前日期的前一天
        String yesterday = today.plusDays(-1).toString();
        return yesterday;
    }

    /**
     * 取得两个日期的时间差 ,差值单位为小时,小时向上取整,如果分钟大于一，小时加1
     *
     * @param date1 日期1
     * @param date2 日期2
     * @return 取得两个日期的时间差
     */
    public static int getUpHourDifference(Date date1, Date date2) {
        int hours = (int) (date2.getTime() - date1.getTime()) / (3600 * 1000);
        int minutes = (int) ((date2.getTime() - date1.getTime()) / (60 * 1000) - hours * 60);
        if (minutes > 0) {
            hours = hours + 1;
        }
        return hours;
    }

//    public static void main(String[] args) {
//        //System.out.println(DateUtil.dateToString(new Date(),DateUtil.defaultTimeFormatStr));
//       // System.out.println(addDateMinut("2020-10-15 23:44" , 3,""));

    /**
     * 获取当前日期的00:00时间
     *
     * @return 取得当前日期得23:59时间
     */
    public static Date getDateStart() {
        LocalDateTime localDateTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(new Date().getTime()), ZoneId.systemDefault());
        LocalDateTime endOfDay = localDateTime.with(LocalTime.MIN);
        return Date.from(endOfDay.atZone(ZoneId.systemDefault()).toInstant());
    }
    /**
     * 获取当前日期的23:59时间
     * @return 取得当前日期得23:59时间
     */
    public static Date getDateEnd() {
        LocalDateTime localDateTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(new Date().getTime()), ZoneId.systemDefault());
        LocalDateTime endOfDay = localDateTime.with(LocalTime.MAX);
        return Date.from(endOfDay.atZone(ZoneId.systemDefault()).toInstant());

    }
    public static Date getDateEnd(Date date){
        LocalDateTime localDateTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(date.getTime()), ZoneId.systemDefault());
        LocalDateTime endOfDay = localDateTime.with(LocalTime.MAX);
        return Date.from(endOfDay.atZone(ZoneId.systemDefault()).toInstant());
    }

    /**
     * 取得系统日期，格式为yyyy-MM-dd
     *
     * @return 系统日期
     */
    public static String getStrDate(Date date) {
        String strDate = "";
        SimpleDateFormat df = new SimpleDateFormat(defaultDateFormatStr);
        strDate = df.format(date);
        return strDate;
    }
    /*
    public static void main(String[] args) {

//        SimpleDateFormat bf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//        System.out.println(getDateEnd());
//        System.out.println(buildDateZero());
//        try {
//            System.out.println(getUpHourDifference(bf.parse(buildDateZero()), getDateEnd()));
//        } catch (ParseException e) {
//            e.printStackTrace();
//        }

         String currTime="2018-01-01 00:00:00";
         System.out.println(addDateSecond(currTime, 10));
    }
    */
}
